package com.ly.listener;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dypnsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dypnsapi20170525.models.CreateVerifySchemeRequest;
import com.aliyun.sdk.service.dypnsapi20170525.models.CreateVerifySchemeResponse;
import com.aliyun.sdk.service.dypnsapi20170525.models.SendSmsVerifyCodeRequest;
import com.aliyun.sdk.service.dypnsapi20170525.models.SendSmsVerifyCodeResponse;
import com.google.gson.Gson;
import com.ly.pojo.Sms;
import com.ly.util.Constant;
import darabonba.core.client.ClientOverrideConfiguration;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.concurrent.CompletableFuture;

@Component
@RocketMQMessageListener(
        topic = Constant.TOPIC_SMS,
        consumerGroup = "sms-consumer-group"
)
public class SmsMessageConsumer implements RocketMQListener<Sms> {

    @Autowired
    private RestTemplate restTemplate; // 注入 RestTemplate

    private final String accessKeyId = "LTAI5tGLpk7UDLEWg7TK31dX";
    private final String accessKeySecret = "eMItn2270pBi1uQn9oBeUS84pZC4kH";
    private final String signName = "速通互联验证码";
    private final String templateCode = "100001";

    @Override
    public void onMessage(Sms sms) {
        System.out.println(sms);
        processSms(sms);

    }
    private void processSms(Sms sms) {
        try {
            //处理sms对象
            sms.setDatesend(new Date());

            // 调用第三方短信服务API（如阿里云、腾讯云短信）
            System.out.println("正在向" + sms.getReceiver() + "发送短信：" + sms.getContent());
            // 这里我选择模拟一个第三方短信服务系统
            // 模拟调用短信接口
            //restTemplate.postForObject(Constant.SMS_SERVICE_URL, sms, Void.class);
            //restTemplate.getForObject("http://localhost:8089/sms/test", Void.class);





            // 调用第三方接口
            // 调用第三方接口
            // 配置认证信息
            /*StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId(accessKeyId)
                    .accessKeySecret(accessKeySecret)
                    .build());

            // 配置客户端
            AsyncClient client = AsyncClient.builder()
                    .region("cn-hangzhou") // 根据实际情况调整region
                    .credentialsProvider(provider)
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    .setEndpointOverride("dypnsapi.aliyuncs.com")
                    )
                    .build();

            try {
                // 构建短信验证码发送请求
                SendSmsVerifyCodeRequest sendSmsVerifyCodeRequest = SendSmsVerifyCodeRequest.builder()
                        .signName(signName)
                        .templateCode(templateCode)
                        .phoneNumber(String.valueOf(sms.getReceiver()))
                        .templateParam("{\"code\":\"" + sms.getContent() + "\",\"min\":\"5\"}")
                        .build();

                // 同步发送短信验证码
                CompletableFuture<SendSmsVerifyCodeResponse> response = client.sendSmsVerifyCode(sendSmsVerifyCodeRequest);
                SendSmsVerifyCodeResponse resp = response.get();

                // 打印响应结果
                System.out.println("短信发送响应: " + new Gson().toJson(resp));

                // 可以根据响应状态判断是否发送成功
                if (resp.getBody() != null && "OK".equals(resp.getBody().getCode())) {
                    System.out.println("阿里云短信发送成功");
                } else {
                    System.err.println("阿里云短信发送失败: " + (resp.getBody() != null ? resp.getBody().getMessage() : "未知错误"));
                    throw new RuntimeException("阿里云短信发送失败");
                }

            } finally {
                // 关闭客户端
                client.close();
            }*/


            System.out.println("短信发送成功");

        } catch (Exception e) {
            System.out.println("短信发送异常，手机号：" + sms.getReceiver() + ", 异常信息: " + e.getMessage());
            // 这里可以根据异常类型决定是否重试
            // 如果抛出异常，消息会根据重试策略重新投递
            throw new RuntimeException("短信发送失败", e);
        }
    }
}
